<template>
  <view class="search-container">
    <view class="search-box">
      <!-- 搜索图标 -->
      <uni-icons
        style="margin-right: 10rpx"
        type="search"
        size="20"
        color="#999"
      ></uni-icons>
      <!-- 输入框 -->
      <input
        class="search-input"
        type="text"
        :placeholder="props.placeholder"
        v-model="searchValue"
        :focus="props.focus ? true : false"
        @input="handleInput"
        @confirm="handleSearch"
      />
      <!-- 清空 -->
      <uni-icons
        type="clear"
        size="18"
        color="#999"
        v-if="searchValue"
        @click="clearFun"
      ></uni-icons>
      <!-- 搜索按钮 -->
      <view
        class="search-btn"
        @click="handleSearch"
        :style="{ color: props.color, borderColor: props.color }"
        >搜索</view
      >
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';

const props = defineProps({
  focus: Boolean,
  color: {
    type: String,
    default: '#007af0',
  },
  placeholder: {
    type: String,
    default: '请输入关键字',
  },
});

// 定义要向父组件传递的事件
const emit = defineEmits(['search', 'clear']);

// 输入框绑定的值
const searchValue = ref('');

// 输入时的处理（可选，可用于实时搜索等场景）
const handleInput = (e) => {
  // 可以在这里做一些实时输入的处理，比如防抖等
};

// 搜索处理
const handleSearch = () => {
  if (searchValue.value.trim() === '') {
    // 可以添加空值提示
    return;
  }
  // 向父组件发射搜索事件，并传递搜索关键字
  emit('search', searchValue.value);
};

const clearFun = () => {
  searchValue.value = '';
  emit('clear');
};
</script>

<style scoped>
.search-containe {
  display: flex;
  flex: 1;
}
.search-box {
  width: 100%;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 33rpx; /* 圆角 */
  height: 66rpx;
  box-sizing: border-box;
  padding: 0 20rpx;
}

.search-input {
  flex: 1;
  font-size: 24rpx;
}

.search-btn {
  font-size: 24rpx;
  color: #007af0;
  margin-left: 30rpx;
  padding-left: 20rpx;
  border-left: 1rpx solid #007af0; /* 分割线 */
}
</style>
